$(function () {
    var $search = parseSearch(),
        strSelectHtml = $('#form-select').html(),
        config = {
            query_store: '/store/queryPinyin?size=300',//分页查询URL,
            getPurchaseOrderBill: '/purchaseOrderBill/query?keyword=send&size=25&goodsId=',

        }, selected = {}, selected_ = {}, detail = {};

    function calculate() {
        var total = 0;
        return getTotal();
    }

    /**
     * 打开选择批号弹框后的初始化
     */
    function initEventWhenSelectBatch() {
        $('.modal-body input[type=checkbox]').unbind('change').change(function (index, item) {
            if ($(this).is(':checked')) {
                if ($('.modal input[type=checkbox]:checked').length == 1) {
                    $(this).data('order', 1);
                } else {
                    var t = $('.modal input[type=checkbox]:checked').map(function (index, item) {
                        if ($(item).data('order') == 'undefined' || $(item).data('order') == undefined) { // 当前元素
                            return 0;
                        }
                        return parseInt($(item).data('order'));
                    });
                    $(this).data("order", _.max(t) + 1);
                }
            }
            getSelectedBatch(this); //

        });
        selected_ = {};
        getSelectedBatch(); // 选择批号
        onInput($('.modal input[type=text]'), function () {
            var max = getCanSend($(this).closest('tr').find('[type=checkbox]').data('json'));
            var inputVal = $(this).val();
            if (parseFloat(inputVal) == NaN) {
                inputVal = 0
            } else {
                inputVal = parseFloat(inputVal);
            }
            if (inputVal > max) {
                $(this).val(max);
            }

        });
    }

    function sortSelected(selects) {
        var selected_1 = {};
        _.sortBy(_.values(selects), 'sort').map(function (item, index) {
            item.sort = index;
            selected_1[item.id] = item;
        });
        return selected_1;
    }

    /**
     *  获取批号可发货数量
     * @param $json
     * @returns {number}
     */
    function getCanSend($json) {
        var tmp_ = 0;
        if ($json.type == 1 && $json.numberReceive > 0) { // 已入库转货权收货单
            var tmp = floatTool.subtract($json.numberReceive, $json.numberSended);//　扣减批号已发货数量
            tmp_ = floatTool.subtract(tmp, $json.numberSending);　// 扣减批号发货中数量
        } else if ($json.type == 2) { // 批号未入库
            var tmp = floatTool.subtract($json.number, $json.numberSended);//　扣减批号已发货数量
            tmp_ = floatTool.subtract(tmp, $json.numberSending);　// 扣减批号发货中数量
        } else { // 批号等于
            tmp_ = $json.number;
        }
        return tmp_;
    }

    /**
     * 初始化选择
     */
    function getSelectedBatch($this) { // 批号先选择先匹配
        selected_ = selected_ || {};
        var total = 0, //
            total_ = calculate(); // 合计需匹配数量
        var restNumForMatch = total_;
        if ($this) {
            var $json = $($this).data('json');
            if ($($this).is(':checked')) {
                selected_ = sortSelected(selected_);
                $json.sort = Object.keys(selected_).length + 1;
                selected_[$json.id] = $json;
            } else {
                delete  selected_[$json.id];
            }
        }

        var st = _.uniq(_.pluck(_.values(selected_), 'storeId'));
        if (st.length > 1) fnFail("所选批号和已选批号仓库地不一致！");
        // 匹配订单
        _.sortBy(_.values(selected_), 'sort').map(function (item) { //
            var $this_ = $('[name=selected' + item.id + ']');
            var $json = $this_.data('json'),
                tmp_ = getCanSend($json); // 批号可使用数量 //

            if (true) {
                var inputVal = $this_.closest('tr').find('[type=text]').val();
                if (restNumForMatch == 0) {
                    return $this_.closest('tr').find('[type=text]').val(0)
                }
                if (parseFloat(inputVal) == NaN) { //  非数字 ，计算
                    inputVal = tmp_;
                } else {
                    inputVal = parseFloat(inputVal);
                    if (inputVal > tmp_ || inputVal == 0) {
                        inputVal = tmp_;
                    }
                }
                if (restNumForMatch >= inputVal) {
                    restNumForMatch = floatTool.subtract(restNumForMatch, inputVal);//
                } else {
                    inputVal = restNumForMatch;
                    restNumForMatch = 0;
                }
                return $this_.closest('tr').find('[type=text]').val(inputVal);

            }

        });
        return total;
    }

    function getTotal() {
        var t = 0;
        detail.data.ladingBillDetail.map(function (item) {
            t = floatTool.add(item.number, t);
        });
        return t;
    }

    function getBatchNumber() {
        var $id = '';
        var url = config.getPurchaseOrderBill + $search.goodsId;
        if ($('[name=type]').val() == 0 || $('[name=type]').val() == 2) {
            url += '&checkStatus=1';
        } else {
            url += '&checkStatus=1&numberReceive=1'
        }
        function getByStore(storeId) {
            var deffer = $.Deferred();
            $.get(url + '&storeId=' + storeId)
                .then(function (res) {
                    deffer.resolve(res);
                });
            return deffer.promise();
        }

        $.when(parent.window.getDataByUrl(config.query_store, 'stores'),
            window.parent.getDataByUrl(url, 'getPurchaseOrderBill' + Math.random()))
            .then(function (stores, res) {

                debugger;
                _alert({
                    width: '95%',
                    title: '选择批号:',
                    body: ejs.render(strSelectHtml, {purchase: res, selected: window.selectedBatch||{}, stores: stores}),
                    show: function () {
                        //initTips(calculate(), 0);
                        $('.modal-body').addClass('min-height250')
                    },
                    shown: function () {
                        var t = getTotal(res);
                        initEventWhenSelectBatch();
                        $('.modal-body input[type=checkbox]').change(function (index, item) {
                            initEventWhenSelectBatch();
                        });
                        // getSelectedBatch($id);
                        $('#store').selectpicker({
                            liveSearch: true
                        })
                            .change(function (e) {
                                getByStore($(this).val())
                                    .then(function (res) {
                                        $('.modal-content table').replaceWith(ejs.render($('#select-batch').html(), {
                                            purchase: res.list,
                                            selected: selected
                                        }));
                                    });

                            })
                    },
                    okHide: function (e) {
                        selected = {};
                        var store = {}, total = 0;
                        window.selectedBatch= {};
                        $('.modal input[type=checkbox]:checked').each(function (index, item) {
                            var $json = $(this).data('json');
                            $json.send = parseFloat($(this).closest('tr').find('input.form-inline').val());
                            total += floatTool.add($json.send, total);
                            store[$json.storeId] = $json;
                            selected[$json.id] = $json;
                            window.selectedBatch[$json.id] = $json.send;
                        });
                        var t = getTotal(res);

                        if (total != t) {
                            fnFail("请足额匹配");
                            return false;
                        }
                        if (!Object.keys(store).length) {
                            fnFail("请选择批号！");
                            return false;
                        }
                        if (Object.keys(store).length > 1) {
                            fnFail("请选择同一个发货仓库");
                            return false;
                        }
                        getStore(Object.keys(store)[0]);
                        var stores = _.values(store);
                        $('[name=storeName]').val(stores[0].storeName);
                        $('[name=storeId]').val(stores[0].storeId);

                        initSelectedBath(_.values(selected));
                        return true;
                    },
                    hasfoot: true
                });
            })
            .fail(function (e) {
                fnFail(e);
            })
    }

    /**
     *  合并收货
     * @param batches
     */
    function initSelectedBath(batches) {// 批号和订单匹配
        var html_ = '', selectedOrder = {}, selectedOrderArray = [];
        $('.send-order').find('tr').each(function (idex, item) {
            var $json = $(this).data('json');
            if ($json) {
                selectedOrder[$json.id] = $json;
                selectedOrderArray.push($json);
            }
        });
        var i_ = 0;
        selectedOrderArray = selectedOrderArray.map(function (item) {
            if (!item.sortOrder) {
                item.sortOrder = 0;
            }
            return item;
        });
        _.sortBy(selectedOrderArray, 'sortOrder').map(function (item, index) {
            var current = batches[i_];
            item.batches = [];
            if (item.number > current.send) { //
                item.send = floatTool.subtract(item.number, current.send); // 剩余需发货
                i_++;
                //item.number = ;//扣减批号匹配数量后剩余可发货数量
                item.batches.push(current);
                var i1 = findNextBatch(batches, i_, item.number);
                for (var j = i_; j < i1; j++) {
                    var batchItem = batches[j];
                    if (item.send > batchItem.send) {
                        item.send = floatTool.subtract(item.send, batchItem.send);
                        item.batches.push($.extend({}, batchItem, {send: item.send}));
                    }
                }
                i_ = i1;
                var tmp = batches[i1];
                if (tmp.send == item.send) { //
                    // item.send = tmp.send;
                    item.send = 0;
                    i_++;
                    item.batches.push($.extend({}, batchItem, {send: tmp.send}));
                } else if (tmp.send > item.send) {
                    item.batches.push($.extend({}, batchItem, {send: item.send}));
                }
            } else if (item.number == current.send) {
                item.send = 0;
                i_++;
                html_ += item.batches.push($.extend({}, current, {send: current.send}));

            } else if (item.number < current.send) {
                item.send = 0;
                current.send = floatTool.subtract(current.send, item.number);
                html_ += item.batches.push($.extend({}, current, {send: item.number}));
            }
            html_ += ejs.render($('#item').html(), {item: item});
            return;
        });
        $('.send-order').find('tbody').html(html_);
        // 插入第一个订单后面
        /***
         * 查询下一个能满足条件的批号
         * @param batches 所选批号
         * @param startIndex 开始索引
         * @param remainTotal 剩余数量
         */
        function findNextBatch(batches, startIndex, remainTotal) {

            var total = 0, i = 0;
            for (i = startIndex; i < batches.length;) {
                var item = batches[i];
                var totalTmp = floatTool.add(total, item.send);
                if (totalTmp < remainTotal) {
                    total = totalTmp;
                    i++;
                } else if (totalTmp > remainTotal) {
                    break;
                } else {
                    break;
                }
            }
            if (i >= batches.length) {
                return batches.length - 1;
            }
            return i;
        }

        initSendNumberThisTime();
        // focusEvent();
        // deleteEvent();
    }

    function initSendNumberThisTime() {
        onInput($('.send-order').find('input'), function () {
            calculate();
        });
        calculate();
    }

    function getStore(storeId) {
        if ($('input[name=type]').val() == 0) {
            $.get('/store/detail/' + storeId, function (res) {
                if (res.code == 200) {
                    if (res.data.showDriver == "1") {
                        if ($('.type-order .driver').length == 0) {
                            var store = '<tr class="driver"> \
                            <td class="td-label">司机姓名：</td> \
                            <td class="td-label-value" style="padding: 1px 8px;"> \
                                <input name="driver" class="form-control"/></td> \
                                <td class="td-label">身份证号：</td> \
                            <td class="td-label-value" style="padding: 1px 8px;">\
                                <input name="driverPhone" class="form-control"/>\
                            </td><td class="td-label"></td> \
                            <td class="td-label-value" style="padding: 1px 8px;"></td></tr>';
                            $(store).insertAfter($('.type-order tr'))
                        }
                    }
                }
            })
        }
    }

    $.get('/ladingBill/get?id=' + $search.id, function (res) {
        detail = res;
        res.data.ladingBill.list = res.data.ladingBillDetail;
        res.data.ladingBillDetail.map(function (item) {
            item.goodsName = res.data.ladingBill.goodsName;
            return item;
        });
        $('.panel-default').append(ejs.render($('#sender-template').html(), res.data.ladingBill));
        var $edit = $('.lading-bill-check-edit');
        onClick($edit, function () {
            var fields = 'carId|driver|driverPhone|expireTime|storeId|storeName';
            fields.split('|').map(function (item) {
                $('[name=' + item + ']').attr('disabled', 'false').prop('disabled', false);
            })
        });

        function getStore(storeId) {
            $.get('/store/detail/' + storeId, function (res) {
                if (res.code == 200) {
                    if (res.data.showDriver == "1") {

                    }
                }
            })
        }

        onClick($('.select-batch'), function () {
            getBatchNumber();
        }); //
        onClick($('.btn-create-lading-bill'), function () {
            var form = $('form').serialize();
            form = parseSearch(form);
            if (form.batchNumbers == 'undefined') {
                fnFail("请选择批号！");
            }
            form.billOrderIds = decodeURIComponent(form.billOrderIds);
            form.batchIds = decodeURIComponent(form.batchIds);
            form.batchNumbers = decodeURIComponent(form.batchNumbers);

            //return alert(JSON.stringify(form));
            $.post('/ladingBill/allow', form, function (res) {
                if (res.code == 200) {
                    alert('操作成功');
                    window.location = './index.html';
                } else {
                    fnFail(res.error || "操作失败");
                }
            });
            return false;
        })
    })

});